﻿using System.Net;
using System.Net.Mail;
using Jayden.Dll.Core;

namespace Jayden.Dll.Web
{
	public class Mailer
	{
		public class MailDestinations
		{
			public MailDestinations() { }
			public MailDestinations(string to) { To = new string[] { to }; }

			public string[] To;
			public string[] Cc;
			public string[] Bcc;
		}
		public class MailContent
		{
			public string Subject;
			public string Body;
		}

		private Configuration m_Configuration;
		private string m_DefaultFromDisplayName = "No-reply";
		private string m_DefaultFromEmail = "admin@localhost";
		private string m_DefaultSmtpHost = "localhost";
		private string m_Username = null;
		private string m_Password = null;
		private bool m_EnableSsl = false;
		private int m_DefaultSmtpPort = 25;

		public Mailer(Configuration config)
		{
			m_Configuration = config;
			m_DefaultFromDisplayName = m_Configuration.GetValue("From/@displayName", m_DefaultFromDisplayName);
			m_DefaultFromEmail = m_Configuration.GetValue("From/@email", m_DefaultFromEmail);
			m_DefaultSmtpHost = m_Configuration.GetValue("Smtp/@host", m_DefaultSmtpHost);
			m_DefaultSmtpPort = int.Parse(m_Configuration.GetValue("Smtp/@port", m_DefaultSmtpPort.ToString()));
			m_Username = m_Configuration.GetValue("Smtp/Credential/@login", null);
			m_Password = m_Configuration.GetValue("Smtp/Credential/@password", null);
			m_EnableSsl = bool.Parse(m_Configuration.GetValue("Smtp/@enableSsl", "false"));
		}

		public void Send(string[] to, string[] cc, string[] bcc, string subject, string body)
		{
			MailMessage message = new MailMessage();
			foreach (string email in to)
				if(!string.IsNullOrWhiteSpace(email))
					message.To.Add(email);
			if(cc != null)
				foreach (string email in cc)
					if (!string.IsNullOrWhiteSpace(email))
						message.CC.Add(email);
			if(bcc != null)
				foreach (string email in bcc)
					if (!string.IsNullOrWhiteSpace(email))
						message.Bcc.Add(email);
			message.Subject = subject;
			message.Body = body;
			message.IsBodyHtml = true;
			message.From = new MailAddress(m_DefaultFromEmail, m_DefaultFromDisplayName);

			SmtpClient smtp = new SmtpClient(m_DefaultSmtpHost, m_DefaultSmtpPort);
			smtp.EnableSsl = m_EnableSsl;
			if (m_Username != null || m_Password != null)
			{
				smtp.UseDefaultCredentials = true;
				smtp.Credentials = new NetworkCredential(m_Username, m_Password);
				//smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
			}
			//smtp.SendAsync(message, null);
			smtp.Send(message);
		}
		public void Send(MailDestinations to, string subject, string body) { Send(to.To, to.Cc, to.Bcc, subject, body); }
		public void Send(MailDestinations to, MailContent content) { Send(to, content.Subject, content.Body); }
	}
}
